/*
 * Copyright 2010 - 2011, The PLDesktop Development Team
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 */

#include "PLJava.h"

#include <PLJavaFile.h>
#include <filetypes/PLJavaConstClassInfo.h>
#include <filetypes/PLJavaConstTypesUtf8.h>
#include <lib/tarfile.h>
#include <machine/machine.h>

using namespace PLSDK;

PLJava::PLJava() : m_files() {
}

void PLJava::startJavaFile(uintptr_t address) {
    PLJavaFile *startFile = new PLJavaFile(address);
    PLJavaConstTypesUtf8 *n = startFile->nameAtIndex(startFile->classValue()->nameIndex());
    if(n) {
        PLJavaFile *file = m_files.lookup(n->string());
        if(file) {
            delete startFile;
            startFile = file;
        } else {
            m_files.insert(n->string(), startFile);
        }
        startFile->runInit();
    } else {
        printf("The name of the class at address 0x%x not exists.", address);
    }
}

void PLJava::addJavaFile(uintptr_t address) {
    PLJavaFile *file = new PLJavaFile(address);
    PLJavaConstTypesUtf8 *n = file->nameAtIndex(file->classValue()->nameIndex());
    if(n) {
        m_files.insert(n->string(), file);
    } else {
        printf("The name of the class at address 0x%x not exists.", address);
    }
}

void PLJava::addJavaFile(const char *classFile) {
    TarFile *classData = 0;
    int strLength = strlen(classFile);
    const char *classString = classFile + (strLength - 6);
    if(strcmp(classString, ".class") != 0) {
        char *compleatFile = new char[strLength + 6 + 8 + 1];
        memcpy(compleatFile, "/initrd/", 8);
        char *classPos = compleatFile + 8;
        memcpy(classPos, classFile, strLength);
        classPos = compleatFile + strLength + 8;
        memcpy(classPos, ".class", 6);
        compleatFile[strLength + 6 + 8] = '\0';
        classData = PLMachine::instance().initrdArchive()->file(compleatFile);
    }
    if(classData && classData->filename()) {
        addJavaFile(classData->startPosition());
    }
}

PLJavaFile *PLJava::javaFile(const char *classFile) {
    return m_files.lookup(classFile);
}
